package com.imy.lua.helper.opencv;

import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.ConditionVariable;

import com.imy.common.util.ALog;
import com.imy.common.util.BitmapUtils;
import com.imy.common.util.UiUtil;
import com.imy.lua.LuaCore;
import com.imy.lua.helper.PointScaleHelper;
import com.imy.lua.helper.properties.PropertiesLoaderHelper;

import org.opencv.core.Mat;
import org.opencv.core.Rect;

import java.io.File;

public class ImageFindHelper {

    private static volatile ImageFindHelper gCore = new ImageFindHelper();
    private boolean mOpenCvInitialized = false;

    public static ImageFindHelper get() {
        return gCore;
    }

    private void initOpenCvIfNeeded() {
        if (mOpenCvInitialized || OpenCVHelper.isInitialized()) {
            return;
        }
        ConditionVariable callLock = new ConditionVariable();
        OpenCVHelper.initIfNeeded(() -> {
            callLock.open();
            mOpenCvInitialized = true;
        });
        callLock.block();
    }

    public Point findImage(String source, String target) {
        return findImage(source, target, 0.9f, null);
    }

    public Point findImage(String source, String target, float threshold, Rect rect) {
        return findImage(source, target, 0.7f, threshold, rect, TemplateMatching.MAX_LEVEL_AUTO);
    }

    /**
     * 仅供测试模块调用 其他模块请使用String 来调用
     *
     * @param source
     * @param target
     * @return
     */
    public Point findImage(ImageWrapper source, ImageWrapper target) {
        return findImage(source, target, 0.9f, null);
    }

    private Point findImage(ImageWrapper source, ImageWrapper target, float threshold, Rect rect) {
        return findImage(source, target, 0.7f, threshold, rect, TemplateMatching.MAX_LEVEL_AUTO);
    }

    private Point findImage(ImageWrapper image, ImageWrapper template,
                            float weakThreshold, float threshold, Rect rect, int maxLevel) {
        //判断是不是同一个分辨率

        initOpenCvIfNeeded();
        if (image == null)
            throw new NullPointerException("image = null");
        if (template == null)
            throw new NullPointerException("template = null");
        Mat src = image.getMat();
        if (rect != null) {
            src = new Mat(src, rect);
        }
        org.opencv.core.Point point = TemplateMatching.fastTemplateMatching(src, template.getMat(), TemplateMatching.MATCHING_METHOD_DEFAULT,
                weakThreshold, threshold, maxLevel);
        if (point != null) {
            if (rect != null) {
                point.x += rect.x;
                point.y += rect.y;
            }
        }
        if (src != image.getMat()) {
            OpenCVHelper.release(src);
        }
        if (point == null) {
            return null;
        }
        return new Point((int) point.x, (int) point.y);
    }


    public Point findImage(String source, String target, float weakThreshold, float threshold, Rect rect, int maxLevel) {
        File sourceFile = new File(source);
        if (!sourceFile.exists()) {
            throw new NullPointerException("sourceFile un exists");
        }
        File targetFile = new File(target);
        ALog.i("findImage target:" + target);
        if (!targetFile.exists()) {
            throw new NullPointerException("targetFile un exists");
        }

        ImageWrapper image = ImageWrapper.ofBitmap(BitmapFactory.decodeFile(source));
        Bitmap targetBitmap = BitmapFactory.decodeFile(target);
        //这里需要判断是不是同分辨率下的 如果是同分辨率下直接使用源文件 如果不是同分辨率 那么需要将bitmap缩放来查找
        ImageWrapper template = ImageWrapper.ofBitmap(targetBitmap);
        return findImage(image, template, weakThreshold, threshold, rect, maxLevel);
    }

    public int getDeviceWidthInPortrait() {
        int orientation = LuaCore.get().getAccessibilityServiceListener().getOrientation();
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            return UiUtil.getDeviceWidth(LuaCore.get().getContext());
        } else {
            return UiUtil.getDeviceHeight(LuaCore.get().getContext());
        }
    }

    public String getScreenFilePath() {
        //替换成对应分辨率的目录文件夹

        int deviceWidthInPortrait = getDeviceWidthInPortrait();
        return String.valueOf(deviceWidthInPortrait);
    }
}
